<?php
// src/Pyaf/GymBundle/Repository/ClaseRepository.php
namespace Pyaf\GymBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Pyaf\GymBundle\Entity\Clase;
/**
 * Description of ClaseRespository
 *
 * @author Toshiba P755-S5272
 */
class ClaseRepository extends EntityRepository{
    
    private $dias = array('Lunes','Martes','Miércoles','Jueves','Viernes');
    private $horas = array( '06', '07', '08', '09', '10', '11',
                            '12', '13', '14', '15', '16', '17', 
                            '18', '19', '20', '21', '22');

    /**
     *  
     * @return a list of Personas order by name
     */
    public function findAllOrderByDia($dia) {        
        return $this->getEntityManager()
                ->createQuery("SELECT c FROM PyafGymBundle:Clase c WHERE c.dia = '$dia' 
                               AND c.habilitado = true
                               ORDER BY c.codigoClase ASC")
                ->getResult();
    }
    
    public function findAllOrderByNombre() {        
        $em = $this->getEntityManager();
        $query = $em->createQuery('SELECT c FROM PyafGymBundle:Clase c ORDER BY c.codigoClase ASC');                
        $claseList = $query->getResult();
        
        if(count($claseList) > 0){
            return $claseList;
        } else {
            return $this->createRecordsClases();
        }
    }
    
    private function createRecordsClases() {
        date_default_timezone_set('America/Argentina/Buenos_Aires');
        try {            
            $em = $this->getEntityManager();
            $clase = new Clase();

            for ($index1 = 0; $index1 < count($this->dias); $index1++) {
                for ($index2 = 0; $index2 < count($this->horas); $index2++) {
                    $clase->setDia($this->dias[$index1]);
                    $clase->setCodigoClase($this->horas[$index2].'-'.$index1);
                    $obj = \DateTime::createFromFormat('H:i:s', $this->horas[$index2].':00:00');                             
                    $clase->setHorario($obj);
                    $clase->setNroCama(3);
                    $clase->setHabilitado(false);
                    $em->persist($clase);
                    $em->flush();
                    $em->clear();
                }
            }
            
            return $this->findAllOrderByNombre();
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

     public function findById($id) {        
        return $this->getEntityManager()
                ->createQuery("SELECT c FROM PyafGymBundle:Clase c WHERE c.id = $id")
                ->getOneOrNullResult();
    }
    
    public function findByCodigo($codigo) {        
        return $this->getEntityManager()
                ->createQuery("SELECT c FROM PyafGymBundle:Clase c WHERE c.codigoClase = '$codigo'")
                ->getOneOrNullResult();
    }
    
    public function findByProfesor($id) {
         return $this->getEntityManager()
                ->createQuery("SELECT c FROM PyafGymBundle:Clase c WHERE c.profesor = '$id'")
                ->getResult();
    }


    public function save($clase){
        $this->saveClase($clase);
    }
    
    public function saveClase($clase) {
        $em = $this->getEntityManager();
        $em->persist($clase);
        $em->flush();
    }
    
    public function updateOrCreate(Clase $clase) {
        $claseEx = new Clase();
        $claseEx = $this->findByCodigo($clase->getCodigoClase());
        $em = $this->getEntityManager();
        if(($claseEx != null) && ($claseEx->getCodigoClase() == $clase->getCodigoClase())){            
            $claseEx->setProfesor($em->find('PyafGymBundle:Profesor', $clase->getProfesor()->getId()));
            $claseEx->setHabilitado($clase->getHabilitado());
            $em->persist($claseEx);
        } else {
            $em->persist($clase);
        }
        $em->flush();
        $em->clear();
    }
    
    public function almacenarCalendarioProfesor($id, $horarios){
        try {
            $em = $this->getEntityManager();
            $em->beginTransaction();
            $clase = new Clase();
            foreach ($horarios as $hs) {
                $clase->setCodigoClase($hs);
                $clase->setHabilitado(true);
                $clase->setProfesor($em->find('PyafGymBundle:Profesor', $id));
                $this->updateOrCreate($clase);
            }
            $em->commit();
        } catch (Exception $exc) {
            $em->rollback();
            throw $exc;
        }
    }
    
    public function disableClase($id){
        $clase = new Clase();
        $clase = $this->getEntityManager()->find('PyafGymBundle:Clase', $id);
        $clase->setHabilitado(false);
        $clase->setProfesor();
        $this->save($clase);
    }
    
    /*
     * ************************************************************************
     */
    public function almacenarCalendarioAlumno($id, $horarios){
        try {
            $em = $this->getEntityManager();
            $em->beginTransaction();
            $clase = new Clase();
            foreach ($horarios as $hs) {
                
                $clase = $em->getRepository('PyafGymBundle:Clase')->findByCodigo($hs);
                $cama = $clase->getNroCama();
                    if($cama > 0){ $cama -= 1;};
                $clase->setNroCama($cama);
                $clase->addAlumno($em->getRepository('PyafGymBundle:Alumno')->findAlumno($id));
                $em->persist($clase);
                $em->flush();
                $em->clear();
            }
            $em->commit();
        } catch (Exception $exc) {
            $em->rollback();
            throw $exc;
        }
    }
    
    public function getClasesAlumno($id){
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder();

        $qb->select(array('a', 'c'))
           ->from('PyafGymBundle:Clase', 'a')
           ->leftJoin('a.alumnos', 'c')
           ->where("c.id = $id");
        $query = $qb->getQuery();
        $results = $query->getResult();

        return $results;
    }
    
    public function getAllClassesFreeSeats(){
        return $this->getEntityManager()
                ->createQuery("SELECT c FROM PyafGymBundle:Clase c WHERE c.nroCama > 0 AND c.habilitado = true")
                ->getResult();
    }
}

?>
